package com.demo.controller;


import com.demo.common.R;
import com.demo.entity.User;
import com.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")

public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public R<User> register(@RequestBody User user) {
        // 1. 参数校验
        if (user.getUserName() == null || user.getUserName().trim().isEmpty()) {
            return R.error("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return R.error("密码不能为空");
        }

        try {
            // 2. 密码加密
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);

            // 3. 注册用户
            boolean success = userService.register(user);
            if (success) {
                user.setPassword(null); // 不返回密码
                return R.success(user); // 返回注册成功的用户信息
            }
            return R.error("注册失败");
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage());
            return R.error(e.getMessage());
        }
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpSession session) {
        log.info("用户登录：{}", user.getUserName());
        // 1. 调用服务层验证登录
        User loggedInUser = userService.login(user.getUserName(), user.getPassword());
        log.info("登录 {}",loggedInUser);
        if (loggedInUser != null) {
            // 2. 登录成功，将用户ID存入Session
            session.setAttribute("userId", loggedInUser.getId());
            log.info("用户 {} 登录成功，ID: {}", user.getUserName(), loggedInUser.getId());
            // 3. 返回用户信息（不包含密码）
            loggedInUser.setPassword(null);
            return R.success(loggedInUser);
        }
        log.warn("用户 {} 登录失败", user.getUserName());
        return R.error("用户名或密码错误");
    }


}
